/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pos.ui.beans;

import com.pos.domain.LineItem;
import com.pos.domain.SaleLineItem;
import com.pos.domain.SalesDetail;
import com.pos.ui.jsf.util.JsfUtil;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.SelectItem;
import javax.inject.Named;

/**
 *
 * @author suraj
 */
@Named("saleBean")
@SessionScoped
public class SaleBean extends TradingBean implements Serializable {

    private List<SaleLineItem> lineItems = new ArrayList<SaleLineItem>();

    public List<SaleLineItem> getLineItems() {
        return lineItems;
    }

    public void addItem() {
        this.lineItems.add((SaleLineItem) this.getLineItem());
        this.itemTransaction.addItem(this.getLineItem());
        this.item = null;
        this.resetLineItem();
    }

    @Override
    public String processRequest() {
        this.baseService.saleItem((SalesDetail) this.itemTransaction);
        JsfUtil.addSuccessMessage("Save Sucessfull");
        return null;
    }

    public SelectItem[] getCustomers() {
        return JsfUtil.getSelectItems(baseService.findAllCustomer(), false);
    }

    public SalesDetail getSaleDetail() {
        return (SalesDetail) this.itemTransaction;
    }

    @Override
    public void reset() {
        this.itemTransaction = new SalesDetail();
        this.item = new SaleLineItem();
    }

    @Override
    public void resetLineItem() {
        this.item = new SaleLineItem();
    }

    @Override
    public LineItem getLineItem() {
        return (SaleLineItem) this.item;
    }

    public double getTotalAmount() {
        double totalCost = 0;
        for (SaleLineItem saleLineItem : lineItems) {
            totalCost += (saleLineItem.getItem().getTotalItemPrice() * saleLineItem.getQuantity());
        }
        return totalCost;
    }

    public String getFormattedTotalAmount() {
        DecimalFormat format = new DecimalFormat("###,###.##");
        return format.format(getTotalAmount());

    }

    public void removeItem(int itemId) {
        for (SaleLineItem saleLineItem : lineItems) {
            if (saleLineItem.getItem().getId() == itemId) {
                this.lineItems.remove(saleLineItem);
            }
        }
    }
}
